import random

from models.models import User
from routes.session import session
# 错误的from routes import session
from utils import log, response_with_headers, http_response
from utils import template

message_list = []

# 多线程：session 可以在服务器端实现过期功能：不能这么写了！！！！！
# session = {
#     'session_id': {
#         'username': 'gua',
#     }
# }


# def current_user(request):
#     session_id = request.cookies.get('user', '')
#     # 被替换username = session.get(session_id, '【游客】')
#     user_id = session.get(session_id, '-1')
#     u = User.find_by(id=user_id)
#     return u


def redirect(location, headers=None):
    if headers is None:
        headers = {
            'Content-Type': 'text/html',
        }
    headers['Location'] = location
    # 302 状态码的含义, Location 的作用
    header = response_with_headers(headers, 302)
    r = header + '\r\n' + ''
    return r.encode(encoding='utf-8')


def random_str():
    """
    生成一个随机的字符串
    """
    seed = 'abcdef'
    s = ''
    for i in range(16):
        # 这里 len(seed) - 2 是因为我懒得去翻文档来确定边界了
        random_index = random.randint(0, len(seed) - 2)
        s += seed[random_index]
    return s


def route_login(request):
    """
    html页面：提交表单request,form-> Server ->routes：form = request.form()-> User.new(form)->渲染html
    """
    headers = {}
    log('login, cookies', request.cookies)
    # username = current_user(request)
    if request.method == 'POST':
        form = request.form()
        # form是dict
        # 修改前
        u = User.new(form)
        # 修改后：
        # u = User(form)
        if u.validate_login():
            user = User.find_by(username=u.username)
            session_id = random_str()
            # 替换原来的session[session_id] = user.username
            session[session_id] = user.id
            headers['Set-Cookie'] = 'user={}'.format(session_id)
            # result = '登录成功'
            return redirect('/', headers)
    # 显示登录页面
    body = template('login.html')
    return http_response(body, headers=headers)


def route_register(request):
    if request.method == 'POST':
        form = request.form()
        u = User.new(form)
        if u.validate_register():
            u.save()
            return redirect('/login')
        else:
            return redirect('/register')
    # 显示注册页面
    body = template('register.html')
    return http_response(body)


# def route_admin_users(request):
#     u = current_user(request)
#     if u is not None and u.is_admin():
#         us = User.all()
#         body = template('admin_users.html', users=us)
#         return http_response(body)
#     else:
#         return redirect('/login')


route_dict = {
    '/login': route_login,
    '/register': route_register,
    # '/admin/users': route_admin_users,
}
